import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {ModalController, AlertController, NavController} from '@ionic/angular';
import {HttpService} from 'src/app/service/http.service';
import {RadioPickModelComponent} from '../../../components/radio-pick-model/radio-pick-model.component';
import {RegionPickModelComponent} from '../../../components/region-pick-model/region-pick-model.component';
import {CheckPickModelComponent} from '../../../components/check-pick-model/check-pick-model.component';
import { ImagePicker } from '@ionic-native/image-picker/ngx';
import { TransferService } from 'src/app/service/transfer.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'app-doctor-personal-center',
    templateUrl: './doctor-personal-center.page.html',
    styleUrls: ['./doctor-personal-center.page.scss'],
})
export class DoctorPersonalCenterPage implements OnInit {
    userData: any = {};
    personName = '';
    personSex = '';
    personTel = '';
    personEmail = '';
    personCollege = '';
    personCH = [];
    personMQ = '';
    personPH = '';
    personSkype = '';
    personRegion = '';
    personDepartment = '';
    personDA = '';
    personRM = '';
    personRegionId = '';
    personDepartmentId = '';
    genderId = 0;
    defaultColumnOptions = [];
    regionBox = [];
    sexBox = [{value: 1, label: 'Male'}, {value: 2, label: 'Female'}];
    payBox = [{value: 1, label: 'DirecAppoint'}, {value: 2, label: 'IndirecAppoint'}];
    personRMId = 0;
    aRegion = '';
    avatarUrl = '';
    sysLang = '';

    constructor(
        private router: Router,
        private httpService: HttpService,
        private navController: NavController,
        private modalController: ModalController,
        private alertController: AlertController,
        private imagePicker: ImagePicker,
        private transferSrv: TransferService,
        private translate: TranslateService,
    ) {
    }

    ngOnInit() {
        this.sysLang = this.translate.getBrowserCultureLang().toLowerCase();
    }

    async ionViewDidEnter() {
        await this.getPersonInfo();
        await this.getDepartments();
        await this.getRegionList();
    }

    async toInfoEdit(type) {
        const editParams: any = {
            dataType: type,
            userType: this.userData.type
        };

        if (type === 'name') {
            editParams.value = this.personName;
        } else if (type === 'email') {
            editParams.value = this.personEmail;
        } else if (type === 'sex') {
            editParams.value = this.personSex;
        } else if (type === 'college') {
            editParams.value = this.personCollege;
        } else if (type === 'MQ') {
            editParams.value = this.personMQ;
            editParams.secondValue = this.userData.medical_qualification;
        } else if (type === 'PH') {
            editParams.value = this.personPH;
        } else if (type === 'PD') {
            editParams.value = this.userData.personal_desc;
        } else if (type === 'TP') {
            editParams.value = this.userData.testing_item;
        } else if (type === 'TestingCost') {
            editParams.value = this.userData.order_price;
        } else if (type === 'PN') {
            editParams.value = this.personTel;
        } else if (type === 'skype') {
            editParams.value = this.personSkype;
        } else if (type === 'region') {
            editParams.value = this.personRegion;
        } else if (type === 'department') {
            editParams.value = this.personDepartment;
        } else if (type === 'DA') {
            editParams.value = this.personDA;
        } else if (type === 'RM') {
            editParams.value = this.personRM;
        }
        await this.router.navigate(['doctor-person-edit'], {
            queryParams: editParams
        });
    }


    public async selectGender() {
        const modal = await this.modalController.create({
            component: RadioPickModelComponent,
            componentProps: {
                title: 'Sex',
                labelProp: 'label',
                selectValue: this.genderId,
                dataList: [...this.sexBox]
            }
        });
        await modal.present();
        const {data} = await modal.onDidDismiss();
        if (!!data) {
            await this.saveData('gender', data.value);
        }
    }

    public async selectOrderMode() {
        const modal = await this.modalController.create({
            component: RadioPickModelComponent,
            componentProps: {
                title: 'ReservationMode',
                labelProp: 'label',
                selectValue: this.personRMId,
                dataList: [...this.payBox]
            }
        });
        await modal.present();
        const {data} = await modal.onDidDismiss();
        if (!!data) {
            await this.saveData('order_type', data.value);
        }
    }

    public async saveData(aKey, aParam) {
        const aUserId = localStorage.getItem('userId');
        const postBody = {};
        postBody[aKey] = aParam;
        const result: any = await this.httpService.put()
            .setPath('/user/doctorUpdate/' + aUserId)
            .setBody({
                ...postBody
            })
            .request();
        if (result.status === 0) {
            const aMessage = this.sysLang === 'en-us' ? 'Save Success' : '保存成功';
            const aText = this.sysLang === 'en-us' ? 'Confirm' : '确定';
            const alert = await this.alertController.create({
                message: aMessage,
                buttons: [
                    {
                        text: aText,
                        handler: () => {
                            this.getPersonInfo();
                        }
                    }
                ]
            });
            await alert.present();
        }
    }

    public async getPersonInfo() {
        const aUserId = localStorage.getItem('userId');
        const result: any = await this.httpService.get()
            .setPath('/user/doctorInfo/' + aUserId)
            .request();
        if (result.status === 0) {
            const aData = result.data;
            this.userData = aData;
            if (!!aData.nickname) {
                this.personName = aData.nickname;
            }
            if (!!aData.email) {
                this.personEmail = aData.email;
            }
            if (!!aData.gender) {
                this.personSex = this.sexBox[aData.gender - 1].label;
                this.genderId = aData.gender;
            }
            if (!!aData.university) {
                this.personCollege = aData.university;
            }
            if (!!aData.hospitalArray) {
                this.personCH = [];
                for (const ahospital of aData.hospitalArray) {
                    this.personCH.push(ahospital.hospital_id);
                }
            }
            if (!!aData.attachment) {
                this.personMQ = aData.attachment_url;
            }
            if (!!aData.personal_honor) {
                this.personPH = aData.personal_honor;
            }
            if (!!aData.phone) {
                this.personTel = aData.phone;
            }
            if (!!aData.skype) {
                this.personSkype = aData.skype;
            }
            if (!!aData.region_id) {
                this.personRegionId = aData.region_id;
                this.personRegion = aData.region_name;
                this.aRegion = aData.region_name;
            }
            if (!!aData.department_id) {
                this.personDepartment = aData.department_name;
                this.personDepartmentId = aData.department_id;
            }
            if (!!aData.address) {
                this.personDA = aData.address;
            }
            if (!!aData.order_type) {
                this.personRM = this.payBox[aData.order_type - 1].label;
                this.personRMId = aData.order_type;
            }
            if (!!aData.avatar_url) {
                this.avatarUrl = aData.avatar_url;
            }
        }
    }

    private async getDepartments() {
        const result: any = await this.httpService.get().setPath('/pub/source/departmentList').request();
        this.defaultColumnOptions = result.data;
    }

    public async getRegionList() {
        const result: any = await this.httpService.get()
            .setPath('/pub/source/threeRegionData')
            .setQuery({
                style: 'tree'
            })
            .request();
        if (result.status === 0) {
            this.regionBox = result.data;
        }
    }

    public async selectRegion() {
        const modal = await this.modalController.create({
            component: RegionPickModelComponent,
            componentProps: {
                title: 'District Choose',
                itemArray: [
                    {
                        name: 'Country Choose',
                        type: 1,
                    },
                    {
                        name: 'State Choose',
                        type: 2,
                    },
                    {
                        name: 'City Choose',
                        type: 3
                    },
                ],
                dataArray: [...this.regionBox]
            }
        });
        await modal.present();
        const {data} = await modal.onDidDismiss();
        if (!!data) {
            this.personRegion = data[2].label;
            this.personRegionId = data[2].value;
            this.saveData('region_id', this.personRegionId);
        }
    }

    public async selectDepartment() {
        const modal = await this.modalController.create({
            component: RadioPickModelComponent,
            componentProps: {
                title: 'Department',
                labelProp: 'name',
                selectValue: this.personDepartmentId,
                dataList: [...this.defaultColumnOptions]
            }
        });
        await modal.present();
        const {data} = await modal.onDidDismiss();
        if (!!data) {
            this.saveData('department_id', data.value);
        }
    }

    public async selectHospital() {
        if (this.personRegion !== this.aRegion) {
            this.personCH = [];
        }
        const result: any = await this.httpService.get()
            .setPath('/pub/source/hospitalList')
            .setQuery({regionId: this.personRegionId, listType: 'simple'})
            .request();
        if (result.status === 0) {
            const modal = await this.modalController.create({
                component: CheckPickModelComponent,
                componentProps: {
                    title: 'CooperativeHospitals',
                    labelProp: 'label',
                    dataList: [...result.data],
                    checkedList: this.personCH,
                }
            });
            await modal.present();
            const {data} = await modal.onDidDismiss();
            if (!!data) {
                this.setHospital(data);
            }
        }
    }

    public async setHospital(aCheckedList) {
        const aUserId = localStorage.getItem('userId');
        const result: any = await this.httpService.put()
            .setPath('/user/bindHospital/' + aUserId)
            .setBody({
                hospitalArray: aCheckedList
            })
            .request();
        if (result.status === 0) {
            const aMessage = this.sysLang === 'en-us' ? 'Save Success' : '保存成功';
            const aText = this.sysLang === 'en-us' ? 'Confirm' : '确定';
            const alert = await this.alertController.create({
                message: aMessage,
                buttons: [
                    {
                        text: aText,
                        handler: () => {
                            this.getPersonInfo();
                        }
                    }
                ]
            });
            await alert.present();
        }
    }
    public async selectImg() {
        const aUserId = localStorage.getItem('userId');
        try {
            const result = await this.imagePicker.getPictures({ maximumImagesCount: 1, quality: 20 });
            const uploadResult = await this.transferSrv.setPath('/upload/file')
                .setFile(result)
                .parseFile()
                .setFieldName('user')
                .setParams({
                    uploadType: 'avatar',
                    userId: aUserId
                })
                .upload();
            if (uploadResult.status === 0) {
                this.avatarUrl = uploadResult.data.resUrl;
            }
        } catch (e) {
            if (HttpService.EnvIndex < 2) {
                alert(JSON.stringify(e));
            }
        }
    }
}
